package com.xqit.ydzhkt.common.exception;

import com.xqit.ydzhkt.common.response.HttpResult;
import com.xqit.ydzhkt.common.response.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Janus on 2020/5/22
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // 声明一个Logger
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return HttpResult
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public HttpResult bizExceptionHandler(HttpServletRequest req, BizException e){
        logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return HttpResult
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public HttpResult exceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常！原因是: {}",e);
        return HttpResult.failure(ResultCodeEnum.NULL_POINTER);
    }

    /**
     * 算术运算异常
     * @param req
     * @param e
     * @return HttpResult
     */
    @ExceptionHandler(value =ArithmeticException.class)
    @ResponseBody
    public HttpResult exceptionHandler(HttpServletRequest req, ArithmeticException e){
        logger.error("发生算术运算异常！原因是: {}",e);
        return HttpResult.failure(ResultCodeEnum.BY_ZERO);
    }

    /**
     * 请求方式错误
     * @param req
     * @param e
     * @return HttpResult
     */
    @ExceptionHandler(value =HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public HttpResult exceptionHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e){
        logger.error("未知异常！原因是: {}",e);
        return HttpResult.failure(ResultCodeEnum.REQUEST_METHOD_NOT_SUPPORTED);
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return HttpResult
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public HttpResult exceptionHandler(HttpServletRequest req, Exception e){
        logger.error("未知异常！原因是: {}",e);
        return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
    }


    //后续异常根据项目具体情况添加

}
